/**
 * 淹没分析演示页面
 * 基于mars3d思路的Cesium淹没分析功能演示
 */
import React, { useEffect, useRef, useState } from 'react';
import { Button, Card, Slider, InputNumber, Space, message, Switch } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, ClearOutlined } from '@ant-design/icons';
import { FloodByGraphic, PolyUtil } from './index';

const FloodAnalysisDemo = () => {
    const cesiumContainerRef = useRef(null);
    const viewerRef = useRef(null);
    const floodByGraphicRef = useRef(null);
    const drawingHandlerRef = useRef(null);
    
    const [isInitialized, setIsInitialized] = useState(false);
    const [isDrawing, setIsDrawing] = useState(false);
    const [hasArea, setHasArea] = useState(false);
    const [isAnalyzing, setIsAnalyzing] = useState(false);
    const [waterLevel, setWaterLevel] = useState(50);
    const [speed, setSpeed] = useState(2);
    const [minHeight, setMinHeight] = useState(0);
    const [maxHeight, setMaxHeight] = useState(100);
    const [currentHeight, setCurrentHeight] = useState(0);
    const [autoPlay, setAutoPlay] = useState(true);
    const [renderMode, setRenderMode] = useState('unified'); // 'unified' or 'grid'
    
    // 初始化Cesium
    useEffect(() => {
        if (!cesiumContainerRef.current) return;
        
        const initializeCesium = async () => {
            try {
                if (!window.Cesium) {
                    message.error('Cesium未加载');
                    return;
                }
                
                const Cesium = window.Cesium;
                
                // 设置Cesium Token
                Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMmZjMmYyZC1lZTkzLTQzYjctYmE2NS01NTQ0NzQyMWZhNDMiLCJpZCI6MTA2NjEsImlhdCI6MTYwNjI4NjY2MH0.PN1-x4vXpC68czogub9X0UDA3GaGE-31PZVbrRyI7CQ';
                
                // 创建Viewer
                const viewer = new Cesium.Viewer(cesiumContainerRef.current, {
                    selectionIndicator: false,
                    animation: false,
                    homeButton: false,
                    geocoder: false,
                    baseLayerPicker: false,
                    timeline: false,
                    fullscreenButton: false,
                    scene3DOnly: true,
                    infoBox: false,
                    sceneModePicker: false,
                    navigationHelpButton: false,
                    terrainProvider: new Cesium.CesiumTerrainProvider({
                        url: Cesium.IonResource.fromAssetId(1)
                    }),
                    skyAtmosphere: false,
                    contextOptions: {
                        webgl: {
                            alpha: true,
                        },
                    },
                });
                
                // 配置场景
                viewer.scene.globe.terrainExaggeration = 1.5;
                viewer.scene.undergroundMode = false;
                viewer.scene.fxaa = true;
                viewer.scene.postProcessStages.fxaa.enabled = true;
                viewer._cesiumWidget._creditContainer.style.display = "none";
                viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString("#041320");
                viewer.scene.backgroundcolor = Cesium.Color.fromCssColorString("#041320");
                viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
                viewer.scene.screenSpaceCameraController.maximumZoomDistance = 50000;
                viewer.scene.globe.depthTestAgainstTerrain = true;
                
                // 设置相机位置（四川某地区）
                viewer.camera.setView({
                    destination: Cesium.Cartesian3.fromDegrees(106.0731, 30.8037, 10000),
                    orientation: {
                        heading: Cesium.Math.toRadians(0),
                        pitch: Cesium.Math.toRadians(-45),
                        roll: 0.0
                    }
                });
                
                viewerRef.current = viewer;
                
                // 创建FloodByGraphic实例
                const floodByGraphic = new FloodByGraphic(viewer, {
                    style: {
                        color: "#007be6",
                        opacity: 0.6,
                        outline: true,
                        renderMode: renderMode
                    }
                });
                
                // 设置事件监听器
                floodByGraphic.on('start', (e) => {
                    console.log('开始淹没分析', e);
                    setIsAnalyzing(true);
                    message.info('开始淹没分析');
                });
                
                floodByGraphic.on('change', (e) => {
                    console.log('淹没高度变化', e);
                    setCurrentHeight(e.height);
                });
                
                floodByGraphic.on('end', (e) => {
                    console.log('淹没分析结束', e);
                    setIsAnalyzing(false);
                    message.success('淹没分析完成');
                });
                
                floodByGraphicRef.current = floodByGraphic;
                setIsInitialized(true);
                
                message.success('3D场景初始化成功');
                
            } catch (error) {
                console.error('初始化失败:', error);
                message.error(`初始化失败: ${error.message}`);
            }
        };
        
        initializeCesium();
        
        return () => {
            if (viewerRef.current) {
                viewerRef.current.destroy();
            }
        };
    }, []);
    
    // 绘制区域
    const drawArea = async () => {
        if (!viewerRef.current || !window.Cesium) return;
        
        const viewer = viewerRef.current;
        const Cesium = window.Cesium;
        
        setIsDrawing(true);
        viewer.cesiumWidget.canvas.style.cursor = 'crosshair';
        
        try {
            // 清除之前的绘制
            viewer.entities.removeAll();
            
            // 开始绘制多边形
            const drawnPositions = await new Promise((resolve, reject) => {
                const positions = [];
                const dynamicPositions = new Cesium.CallbackProperty(() => {
                    return new Cesium.PolygonHierarchy(positions);
                }, false);
                
                const dynamicPolygon = viewer.entities.add({
                    name: 'DrawingPolygon',
                    polygon: {
                        hierarchy: dynamicPositions,
                        material: Cesium.Color.YELLOW.withAlpha(0.3),
                        outline: true,
                        outlineColor: Cesium.Color.RED,
                        outlineWidth: 2
                    }
                });
                
                const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
                
                handler.setInputAction((event) => {
                    const pickedPosition = viewer.scene.pickPosition(event.position);
                    if (pickedPosition) {
                        positions.push(pickedPosition);
                    }
                }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
                
                handler.setInputAction(() => {
                    if (positions.length < 3) {
                        message.warning('至少需要绘制3个点');
                        return;
                    }
                    
                    handler.destroy();
                    viewer.entities.remove(dynamicPolygon);
                    resolve(positions);
                }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
                
                // 添加鼠标移动事件
                handler.setInputAction((event) => {
                    if (positions.length > 0) {
                        const pickedPosition = viewer.scene.pickPosition(event.endPosition);
                        if (pickedPosition) {
                            const dynamicPositions = [...positions, pickedPosition];
                            // 更新动态多边形
                        }
                    }
                }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
                
                drawingHandlerRef.current = handler;
            });
            
            // 绘制完成，创建最终的分析区域
            const finalPolygon = viewer.entities.add({
                name: 'AnalysisArea',
                polygon: {
                    hierarchy: drawnPositions,
                    material: Cesium.Color.GREEN.withAlpha(0.3),
                    outline: true,
                    outlineColor: Cesium.Color.GREEN,
                    outlineWidth: 3
                }
            });
            
            // 计算区域的高程信息
            message.loading('正在计算区域高程信息...', 0);
            const result = await PolyUtil.interPolygonByDepth({
                scene: viewer.scene,
                positions: drawnPositions
            });
            
            message.destroy();
            
            setMinHeight(result.minHeight);
            setMaxHeight(result.maxHeight);
            setWaterLevel(result.avgHeight || result.minHeight + 10);
            setHasArea(true);
            
            message.success(`区域绘制完成！高程范围: ${result.minHeight.toFixed(2)}m ~ ${result.maxHeight.toFixed(2)}m`);
            
            // 设置FloodByGraphic的参数
            floodByGraphicRef.current.setOptions({
                positions: drawnPositions,
                minHeight: result.minHeight,
                maxHeight: result.maxHeight,
                speed: speed,
                style: {
                    color: "#007be6",
                    opacity: 0.6,
                    outline: true,
                    renderMode: renderMode
                }
            });
            
        } catch (error) {
            console.error('绘制失败:', error);
            message.error(`绘制失败: ${error.message}`);
        } finally {
            setIsDrawing(false);
            viewer.cesiumWidget.canvas.style.cursor = 'default';
        }
    };
    
    // 开始淹没分析
    const startAnalysis = () => {
        if (!floodByGraphicRef.current || !hasArea) {
            message.warning('请先绘制分析区域');
            return;
        }
        
        // 更新参数
        floodByGraphicRef.current.setOptions({
            minHeight: minHeight,
            maxHeight: waterLevel,
            speed: speed
        });
        
        floodByGraphicRef.current.start();
    };
    
    // 停止淹没分析
    const stopAnalysis = () => {
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.stop();
        }
    };
    
    // 清除分析结果
    const clearAnalysis = () => {
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.clear();
        }
        if (viewerRef.current) {
            viewerRef.current.entities.removeAll();
        }
        setHasArea(false);
        setIsAnalyzing(false);
        setCurrentHeight(0);
        message.info('已清除分析结果');
    };
    
    // 手动设置水位高度
    const onHeightChange = (value) => {
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.height = value;
            setCurrentHeight(value);
        }
    };
    
    // 渲染模式改变
    const onRenderModeChange = (checked) => {
        const newMode = checked ? 'unified' : 'grid';
        setRenderMode(newMode);
        
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.options.style.renderMode = newMode;
        }
    };
    
    return (
        <div style={{ width: '100%', height: '100vh', position: 'relative' }}>
            {/* 3D场景容器 */}
            <div 
                ref={cesiumContainerRef} 
                style={{ 
                    width: '100%', 
                    height: '100%',
                    background: '#041320'
                }}
            />
            
            {/* 控制面板 */}
            <Card
                title="淹没分析控制面板"
                style={{
                    position: 'absolute',
                    top: 20,
                    left: 20,
                    width: 350,
                    maxHeight: 'calc(100vh - 40px)',
                    overflowY: 'auto'
                }}
                size="small"
            >
                <Space direction="vertical" style={{ width: '100%' }}>
                    {/* 基础操作 */}
                    <div>
                        <h4>基础操作</h4>
                        <Space>
                            <Button 
                                type="primary" 
                                onClick={drawArea}
                                disabled={!isInitialized || isDrawing}
                                loading={isDrawing}
                            >
                                {isDrawing ? '绘制中...' : '绘制区域'}
                            </Button>
                            <Button 
                                onClick={clearAnalysis}
                                disabled={!isInitialized}
                                icon={<ClearOutlined />}
                            >
                                清除
                            </Button>
                        </Space>
                    </div>
                    
                    {/* 参数设置 */}
                    <div>
                        <h4>参数设置</h4>
                        <Space direction="vertical" style={{ width: '100%' }}>
                            <div>
                                <label>最低高程 (m):</label>
                                <InputNumber
                                    value={minHeight}
                                    onChange={setMinHeight}
                                    style={{ width: '100%' }}
                                    step={0.1}
                                    precision={1}
                                />
                            </div>
                            <div>
                                <label>目标水位 (m):</label>
                                <InputNumber
                                    value={waterLevel}
                                    onChange={setWaterLevel}
                                    style={{ width: '100%' }}
                                    step={0.1}
                                    precision={1}
                                />
                            </div>
                            <div>
                                <label>淹没速度 (m/s):</label>
                                <InputNumber
                                    value={speed}
                                    onChange={setSpeed}
                                    style={{ width: '100%' }}
                                    step={0.1}
                                    precision={1}
                                    min={0.1}
                                    max={10}
                                />
                            </div>
                            <div>
                                <label>渲染模式:</label>
                                <Switch
                                    checked={renderMode === 'unified'}
                                    onChange={onRenderModeChange}
                                    checkedChildren="统一"
                                    unCheckedChildren="网格"
                                />
                            </div>
                        </Space>
                    </div>
                    
                    {/* 分析控制 */}
                    <div>
                        <h4>分析控制</h4>
                        <Space>
                            <Button 
                                type="primary"
                                onClick={startAnalysis}
                                disabled={!hasArea || isAnalyzing}
                                icon={<PlayCircleOutlined />}
                            >
                                开始分析
                            </Button>
                            <Button 
                                onClick={stopAnalysis}
                                disabled={!isAnalyzing}
                                icon={<PauseCircleOutlined />}
                            >
                                停止分析
                            </Button>
                        </Space>
                    </div>
                    
                    {/* 实时水位调节 */}
                    {hasArea && (
                        <div>
                            <h4>实时水位调节</h4>
                            <div>
                                <label>当前水位: {currentHeight.toFixed(1)}m</label>
                                <Slider
                                    min={minHeight}
                                    max={Math.max(waterLevel, maxHeight)}
                                    value={currentHeight}
                                    onChange={onHeightChange}
                                    step={0.1}
                                    tooltip={{ formatter: (value) => `${value.toFixed(1)}m` }}
                                />
                            </div>
                        </div>
                    )}
                    
                    {/* 状态信息 */}
                    <div>
                        <h4>状态信息</h4>
                        <div style={{ fontSize: '12px', color: '#666' }}>
                            <div>场景状态: {isInitialized ? '已初始化' : '初始化中...'}</div>
                            <div>分析区域: {hasArea ? '已绘制' : '未绘制'}</div>
                            <div>分析状态: {isAnalyzing ? '进行中' : '已停止'}</div>
                            <div>当前水位: {currentHeight.toFixed(1)}m</div>
                        </div>
                    </div>
                </Space>
            </Card>
            
            {/* 操作提示 */}
            <div
                style={{
                    position: 'absolute',
                    bottom: 20,
                    left: 20,
                    background: 'rgba(0,0,0,0.7)',
                    color: 'white',
                    padding: '10px',
                    borderRadius: '4px',
                    fontSize: '12px'
                }}
            >
                <div>操作提示:</div>
                <div>• 点击"绘制区域"开始绘制分析区域</div>
                <div>• 左键点击添加点，右键点击完成绘制</div>
                <div>• 设置参数后点击"开始分析"</div>
                <div>• 可以实时调节水位滑块观看效果</div>
            </div>
        </div>
    );
};

export default FloodAnalysisDemo; 